<template>
  <div class="activities-container">
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="活动标题/地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            style="width: 150px"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态">
          <el-select
            v-model="searchForm.publish_status"
            placeholder="请选择状态"
            style="width: 150px"
            clearable
          >
            <el-option
              v-for="item in publishStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="title">活动列表</span>
          <div class="button-group">
            <el-button type="primary" @click="handleAdd">新增活动</el-button>
            <el-button
              type="danger"
              :disabled="!selectedRows.length"
              @click="handleBatchDelete"
              >批量删除</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="200" align="center" />
        <el-table-column label="封面图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.pic"
              :src="getImageUrl(row.pic)"
              fit="cover"
              class="activity-image"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="活动标题" min-width="250" />
        <el-table-column prop="price" label="价格" width="100" align="center">
          <template #default="{ row }"> ¥{{ row.price }} </template>
        </el-table-column>
        <el-table-column
          prop="enrollment"
          label="报名人数"
          width="100"
          align="center"
        />
        <el-table-column prop="address" label="活动地点" width="180" />
        <el-table-column
          prop="status"
          label="活动状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === 0
                  ? 'warning'
                  : row.status === 1
                    ? 'success'
                    : 'info'
              "
            >
              {{
                row.status === 0
                  ? "未开始"
                  : row.status === 1
                    ? "进行中"
                    : "已结束"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="startTime"
          label="开始时间"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="endTime"
          label="结束时间"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              v-if="row.publish_status === 0"
              link
              type="success"
              @click="handlePublish(row)"
            >
              发布
            </el-button>
            <el-button v-else link type="warning" @click="handleUnpublish(row)">
              下架
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑活动对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增活动' : '编辑活动'"
      width="650px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>

        <el-form-item label="封面图片" prop="pic">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.pic" :src="getImageUrl(form.pic)" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            :step="10"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="address">
          <el-input v-model="form.address" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
            v-model="form.activityTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="店铺" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择店铺">
            <el-option
              v-for="item in storeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { getActivitiesList } from "@/api/activities";
import { formatDateTime as formatDate } from "@/utils/date";
import { formatImageUrl } from "@/utils/tools";

// 状态选项
const statusOptions = [
  { label: "未开始", value: 0 },
  { label: "进行中", value: 1 },
  { label: "已结束", value: 2 }
];

// 发布状态选项
const publishStatusOptions = [
  { label: "未发布", value: 0 },
  { label: "已发布", value: 1 }
];

// 店铺选项，实际项目中可能需要从API获取
const storeOptions = [{ label: "拾光锦汉服体验馆", value: "1" }];

// 搜索表单
const searchForm = reactive({
  keyword: "",
  status: undefined,
  publish_status: undefined,
  dateRange: []
});

// 表格数据相关
const loading = ref(false);
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("add"); // add 或 edit
const formRef = ref(null);
const form = reactive({
  id: "",
  title: "",
  pic: "",
  price: 0,
  address: "",
  activityTime: [], // 用于日期选择器
  storeId: "1",
  enrollment: "0",
  status: 0,
  startTime: "",
  endTime: ""
});

// 表单验证规则
const formRules = {
  title: [{ required: true, message: "请输入活动标题", trigger: "blur" }],
  pic: [{ required: true, message: "请上传活动封面图片", trigger: "change" }],
  price: [{ required: true, message: "请输入活动价格", trigger: "blur" }],
  address: [{ required: true, message: "请输入活动地点", trigger: "blur" }],
  activityTime: [
    { required: true, message: "请选择活动时间", trigger: "change" }
  ],
  storeId: [{ required: true, message: "请选择店铺", trigger: "change" }]
};

// 获取图片URL
const getImageUrl = pic => {
  return formatImageUrl(pic);
};

// 格式化日期时间
const formatDateTime = dateTime => {
  if (!dateTime) return "-";
  return formatDate(dateTime);
};

// 获取活动列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params: any = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      status: searchForm.status,
      publish_status: searchForm.publish_status
    };

    // 添加关键词搜索
    if (searchForm.keyword) {
      params.keyword = searchForm.keyword;
    }

    // 添加日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0];
      params.endDate = searchForm.dateRange[1];
    }

    const res = await getActivitiesList(params);
    if (res.code === 200) {
      tableData.value = res.data.result || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.message || "获取活动列表失败");
    }
  } catch (error) {
    console.error("获取活动列表出错", error);
    ElMessage.error("获取活动列表出错");
  } finally {
    loading.value = false;
  }
};

// 页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  fetchData();
};

// 每页数量变化
const handleSizeChange = val => {
  pageSize.value = val;
  fetchData();
};

// 多选变化
const handleSelectionChange = selection => {
  selectedRows.value = selection;
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (key === "dateRange") {
      searchForm[key] = [];
    } else {
      searchForm[key] = undefined;
    }
  });
  currentPage.value = 1;
  fetchData();
};

// 新增活动
const handleAdd = () => {
  dialogType.value = "add";
  resetForm();
  dialogVisible.value = true;
};

// 编辑活动
const handleEdit = row => {
  dialogType.value = "edit";
  resetForm();

  // 填充表单数据
  Object.keys(form).forEach(key => {
    if (key in row) {
      form[key] = row[key];
    }
  });

  // 设置活动时间
  if (row.startTime && row.endTime) {
    form.activityTime = [row.startTime, row.endTime];
  }

  dialogVisible.value = true;
};

// 删除活动
const handleDelete = row => {
  ElMessageBox.confirm("确定要删除该活动吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        // 实际项目中这里应该调用删除API
        ElMessage.success("删除成功");
        fetchData();
      } catch (error) {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      try {
        // 实际项目中这里应该调用批量删除API
        ElMessage.success("批量删除成功");
        fetchData();
      } catch (error) {
        ElMessage.error("批量删除失败");
      }
    })
    .catch(() => {});
};

// 发布活动
const handlePublish = row => {
  ElMessageBox.confirm("确定发布该活动吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info"
  })
    .then(async () => {
      try {
        // 实际项目中这里应该调用发布API
        ElMessage.success("发布成功");
        fetchData();
      } catch (error) {
        ElMessage.error("发布失败");
      }
    })
    .catch(() => {});
};

// 下架活动
const handleUnpublish = row => {
  ElMessageBox.confirm("确定下架该活动吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        // 实际项目中这里应该调用下架API
        ElMessage.success("下架成功");
        fetchData();
      } catch (error) {
        ElMessage.error("下架失败");
      }
    })
    .catch(() => {});
};

// 上传图片成功回调
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code === 200) {
    form.pic = response.data;
    ElMessage.success("上传成功");
  } else {
    ElMessage.error(response.message || "上传失败");
  }
};

// 上传前校验
const beforeAvatarUpload = file => {
  const isJPG =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/webp";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传封面图片只能是 JPG/PNG/WEBP 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传封面图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  form.id = "";
  form.title = "";
  form.pic = "";
  form.price = 0;
  form.address = "";
  form.activityTime = [];
  form.storeId = "1";
  form.enrollment = "0";
  form.status = 0;
  form.startTime = "";
  form.endTime = "";
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      // 处理活动时间
      if (form.activityTime && form.activityTime.length === 2) {
        form.startTime = form.activityTime[0];
        form.endTime = form.activityTime[1];
      }

      try {
        // 实际项目中这里应该调用新增或编辑API
        if (dialogType.value === "add") {
          ElMessage.success("添加成功");
        } else {
          ElMessage.success("更新成功");
        }
        dialogVisible.value = false;
        fetchData();
      } catch (error) {
        ElMessage.error(dialogType.value === "add" ? "添加失败" : "更新失败");
      }
    } else {
      return false;
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.activities-container {
  padding: 15px;
}

.search-card {
  margin-bottom: 15px;
}

.table-card {
  margin-bottom: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.activity-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  object-fit: cover;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>
